package com.zeratul.common.mybatis.utils;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Proxy;

public class MyBatisUtils {

    /**
     * 获得最终的目标对象
     * @return
     */
    public static Object getNoProxyTraget(Object target){
        // 使用Java标准API检查是否为代理对象，并获取目标对象
        while (Proxy.isProxyClass(target.getClass())) {
            // 如果是JDK动态代理
            target = Proxy.getInvocationHandler(target);
            try {
                // 尝试获取目标对象
                MetaObject metaObject = SystemMetaObject.forObject(target);
                if (metaObject.hasGetter("target")) {
                    target = metaObject.getValue("target");
                } else {
                    break;
                }
            } catch (Exception e) {
                // 如果访问失败，则跳出循环
                break;
            }
        }
        return target;
    }

    /**
     * 查询主表from的位置
     * @param begin - 开始查询的位置
     * @param sql - 需要查询的sql语句
     * @return
     */
    public static int selectFromIndex(int begin, String sql){
        int count = 0;//括号的数量
        int fromIndex = sql.indexOf("from", begin);

        //搜索位置
        int selectIndex = fromIndex;
        int bIndex = -1;
        while((bIndex = sql.lastIndexOf("(", selectIndex)) != -1){
            count++;
            selectIndex = bIndex - 1;
        }

        //搜索反括号
        selectIndex = fromIndex;
        int eIndex = -1;
        while((eIndex = sql.lastIndexOf(")", selectIndex)) != -1){
            count--;
            selectIndex = eIndex - 1;
        }

        if (count == 0) {
            return fromIndex;
        } else {
            return selectFromIndex(fromIndex + 1, sql);
        }
    }
}
